﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FlyingEye.HttpServices;
using FlyingEye.SaveInfos;
using FlyingEye.SaveInfoServices;
using FlyingEye.Views;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Net.Http;
using System.Windows;
using System.Windows.Input;

namespace FlyingEye.ViewModels
{
    public class AuthenticationWindowViewModel : ObservableObject
    {
        private readonly ILogger<AuthenticationWindowViewModel> _logger;

        private readonly HttpClientServiceOptions _options;

        public string UserName { get; set; }

        public string Password { get; set; }

        public ICommand LoginCommand { get; set; }

        private readonly IHttpClientFactory _httpClientFactory;

        private Visibility _loadingVisibility;

        public Visibility LoadingVisibility
        {
            get { return _loadingVisibility; }
            set
            {
                IsEnabled = LoadingVisibility == Visibility.Visible;
                SetProperty(ref _loadingVisibility, value);
            }
        }

        private bool _isEnabled;

        public bool IsEnabled
        {
            get { return _isEnabled; }
            set { SetProperty(ref _isEnabled, value); }
        }

        public AuthenticationWindowViewModel(
            IOptions<HttpClientServiceOptions> options,
            IHttpClientFactory httpClientFactory,
            ILogger<AuthenticationWindowViewModel> logger)
        {
            UserName = "admin";
            Password = "";
            LoginCommand = new RelayCommand<AuthenticationWindow>(OnLogin);
            _options = options.Value;
            _httpClientFactory = httpClientFactory;
            this.LoadingVisibility = Visibility.Hidden;
            _logger = logger;
            OnLoad();
        }

        private void OnLoad()
        {
            try
            {
                var saveInfo = SaveInfo.Read<UserInputSaveInfo>();
                UserName = string.IsNullOrWhiteSpace(saveInfo.UserName) ? "admin" : saveInfo.UserName;
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Show("读取保存信息错误！", "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
                _logger.LogError(ex, ex.Message);
            }
        }
        private void Save()
        {
            try
            {
                var saveInfo = SaveInfo.Read<UserInputSaveInfo>();
                saveInfo.UserName = UserName;
                SaveInfo.Write(saveInfo);
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Show("保存信息错误！", "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
                _logger.LogError(ex, ex.Message);
            }
        }


        private async void OnLogin(AuthenticationWindow? window)
        {
            Password = window?.PasswordBox.Password ?? string.Empty;

            if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password))
            {
                HandyControl.Controls.MessageBox.Show("用户名和密码不能为空！", "错误", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            using var httpClient = _httpClientFactory.CreateClient("AuthenticationHttpClient");
            httpClient.Timeout = TimeSpan.FromSeconds(10);

            var requestContent = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                {"client_id", _options.ClientId },
                {"client_secret", _options.ClientSecret },
                {"grant_type", "password" },
                {"username", UserName.Trim() },
                {"password", Password.Trim() }
            });

            OpenLoading(); // 打开加载动画
            Save(); // 保存用户名

            try
            {
                await Task.Delay(1000);
                var response = await httpClient.PostAsync(_options.AuthUrl, requestContent);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    if (window != null)
                    {
                        window.DialogResult = true;
                        window.Close();
                    }
                }
                else
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        HandyControl.Controls.MessageBox.Show(
                       "认证失败，请检查用户名和密码。",
                       "认证提示",
                       MessageBoxButton.OK,
                       MessageBoxImage.Information);
                    }
                    else
                    {
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户认证失败！");
                HandyControl.Controls.MessageBox.Show(
                        "应用程序错误，认证失败！",
                        "错误提示",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
            }
            finally
            {
                CloseLoading();
            }
        }

        private void OpenLoading()
        {
            LoadingVisibility = Visibility.Visible;
        }

        private void CloseLoading()
        {
            LoadingVisibility = Visibility.Hidden;
        }
    }
}
